<?php
namespace Anchu\Zzd\Login;

/**
 * Class 对接浙江乡村大脑登录
 * @package Anchu\Zhelb\Login
 */
class XcdnLogin
{
    const USERINFO_URL = 'https://szsn.zjagri.cn/gateway/oauth2/userinfo';
    const TOKEN_URL = 'https://szsn.zjagri.cn/gateway/oauth2/token';

    private $appKey;
    private $appSecret;

    /**
     * 获取浙江乡村大脑的
     * @param $appKey : 在irs平台上发起对接申请通过后获取到的client_id
     * @param $appSecret : 在irs平台上发起对接申请通过后获取到的sk
     */
    public function __construct($appKey, $appSecret)
    {
        $this->appKey = $appKey;
        $this->appSecret = $appSecret;
    }

    /**
     * 获取用户信息
     * @param string $code
     * @return bool|string
     */
    public function getUserInfo($code = '')
    {
        list($accessToken,) = $this->getAccessToken($code);
        $httpParams = [
            'access_token' => $accessToken
        ];
        return $this->curl(self::USERINFO_URL, $httpParams);
    }


    /**
     * 获取浙江乡村大脑的code
     * @param string $code
     * @return array
     */
    public function getAccessToken($code = '')
    {
        $httpParams = [
            'grant_type' => 'authorization_code',
            'client_id' => $this->appKey,
            'client_secret' => $this->appSecret,
            'code' => $code,
        ];
        $res = $this->curl(self::TOKEN_URL, $httpParams);
        if (!isset($res['code']) || $res['code'] != 200) {
            throw new \Exception($res['message'] ?? '获取accessToken失败');
        }
        $data = $res['data'] ?? [];
        $accessToken = $data['access_token'];
        $refreshToken = $data['refresh_token'];
        return [$accessToken, $refreshToken];
    }

    /**
     * 工具，此处使用
     * @param $url
     * @return bool|string
     */
    private function curl($url, $params = [], $method = 'GET')
    {
        try {
            $ch = curl_init();
            if ($method == 'GET') {
                $paramsList = [];
                foreach ($params as $key => $value) {
                    $paramsList[] = $key . '=' . $value;
                }
                $url = $url . '?' . implode('&', $paramsList);
                curl_setopt($ch, CURLOPT_POST, false);
            }

            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            // 取消结果自动打印
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $res = curl_exec($ch);
            curl_close($ch);
            return json_decode($res, 1);
        } catch (\Exception $e) {
            exit($e->getMessage());
        }
    }
}